<?php

namespace App\Model;

use App\BaseModel;
use App\Helpers\Helpers;
use Illuminate\Support\Facades\DB;

class WineCoupon extends BaseModel
{
    protected $table = "wine_coupons";

    protected $fillable = [
        'name',
        'coupon_category_id',
        'can_get_start',
        'can_get_end',
        'enable_use_date',
        'enable_use_days',
        'can_use_start',
        'can_use_end',
        'can_use_days',
        'condition',
        'sku',
        'coupon_name',
        'user_id',
        'updater',
        'creator',
    ];

    public function category()
    {
        return $this->belongsTo('App\Model\WineCouponCategory','coupon_category_id','id');
    }

    public function users()
    {
        return $this->hasMany('App\Model\UserCoupon','coupon_id','id');
    }

    //更新统计
    public function updateChat()
    {
        return self::updateChatByCouponId($this->id);
    }

    //更新统计(数组)
    public static function updateChatByCouponIds($coupon_ids)
    {
        foreach ($coupon_ids as $coupon_id){
            self::updateChatByCouponId($coupon_id);
        }
        return count($coupon_ids);
    }
    //更新统计
    public static function updateChatByCouponId($coupon_id)
    {
        $db = DB::table('t_user_coupons')->where('coupon_id','=',$coupon_id);
        $get = $db->count();
        $use = $db->where('state','=',1)->count();
        return DB::table('wine_coupons')->where('id','=',$coupon_id)->update([
            'used' => $use,
            'get' => $get
        ]);
    }

    public function createCode()
    {
        if (!$this->code){
            $this->code = Helpers::createCouponCode();
            return $this->save();
        }
        return false;
    }
}
